package com.example.demo.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.pgsql", sqlSessionTemplateRef = "pgSqlSqlSessionTemplate")
public class PgSqlDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource pgSqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @DependsOn("pgSqlDataSource")
    public SqlSessionFactory pgSqlSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(pgSqlDataSource());
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/example/demo/mapper/pgsql/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    @DependsOn("pgSqlSqlSessionFactory")
    public SqlSessionTemplate pgSqlSqlSessionTemplate() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(pgSqlSqlSessionFactory());
        return template;
    }
}
